#include "Bomb.h"
#include "CustomModel.h"

Bomb::Bomb(double _x, double _y):
PhysicObject(b2_staticBody, _x, _y, "mine"),
myself(NULL),
expl(0)
{
	b2CircleShape shape;
	shape.m_radius = .5;

	width = 1 * Config::PHYSIC_SCALE;
	height = 1 * Config::PHYSIC_SCALE;

	b2FixtureDef fix;
	fix.shape = &shape;
	fix.isSensor = true;

	addFixture(&fix);
}

Bomb::~Bomb(void)
{
	(*myself) = NULL;
}

void Bomb::update()
{
	if(expl)
	{
		b2Body *target;
		b2Vec2 vel(500,0);

		b2ContactEdge *list = body->GetContactList();
		while(list)
		{
			if( list->contact->IsTouching() )
			{
				target = list->contact->GetFixtureA()->GetBody();
				vel = target->GetWorldCenter();
				vel = vel - body->GetWorldCenter();
				vel *= (200/vel.Length());
				target->ApplyLinearImpulse(vel, body->GetWorldCenter() );
				target->ApplyAngularImpulse(vel.Length()*1.3);

				/*target = list->contact->GetFixtureB()->GetBody();
				vel = target->GetWorldCenter();
				vel = vel - body->GetWorldCenter();
				vel *= (500/vel.Length());
				target->ApplyLinearImpulse(vel, body->GetWorldCenter() );*/
			}
			list = list->next;
		}
		static_cast<CustomModel *>(CustomModel::getModel())->explosion.play();
		clearInstance();
		return;
	}

	b2ContactEdge *list = body->GetContactList();
	while(list)
	{
		if( list->contact->IsTouching() )
		{
			explode();
			break;
		}
		list = list->next;
	}
}

void Bomb::explode()
{
	b2CircleShape shape;
	shape.m_radius = 10;//3

	width = 18 * Config::PHYSIC_SCALE;
	height = 18 * Config::PHYSIC_SCALE;

	b2FixtureDef fix;
	fix.shape = &shape;
	fix.isSensor = true;

	addFixture(&fix);

	expl = 1;
	visible = false;
}

void Bomb::clearInstance()
{
	if(!myself)
		allegro_message("myself pointer can not be null!");
	*myself = NULL;
	delete this;
}